<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch">
      <el-row :gutter="10">
        <el-col :span="4">
          <el-form-item prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入接口名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dict:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:dict:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:dict:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-close"
          size="mini"
          @click="handleClose"
        >关闭</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-table height="0" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center">
        <template v-slot="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="接口名称" align="center" prop="name" />
      <el-table-column label="序列号" align="center" prop="serialNumber" />

      <el-table-column label="接口描述" align="center" prop="description" />

      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dict:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dict:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body center :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="接口名称">
          <el-input size="small" v-model="form.name" placeholder="请输入接口名称" />
        </el-form-item>
        <el-form-item label="序列号" prop="serialNumber">
          <el-input size="small" v-model="form.serialNumber" placeholder="请输入序列号" />
        </el-form-item>
        <el-form-item label="接口描述" prop="dictValue">
          <el-input size="small" v-model="form.description" placeholder="请输入接口描述" />
        </el-form-item>
        <el-form-item label="请求路径" prop="cssClass">
          <el-input size="small" v-model="form.requestUrl" placeholder="http://" />
        </el-form-item>

        <el-form-item label="请求方法" prop="requestMethod">
          <el-select size="small" v-model="form.requestMethod">
            <el-option
              v-for="item in requestMethodOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.usageStatus">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="请求头" prop="requestHeader">
          <el-input v-model="form.requestHeader" rows="5" placeholder="请输入请求头(json)" type="textarea" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" rows="5" type="textarea" placeholder="请输入备注" />
        </el-form-item>

        <el-form-item label="请求参数" prop="requestParams">
          <el-table
            :data="paramsData"
            style="width: 100%">
            <el-table-column prop="date" label="序号" width="80">
              <template v-slot="scope">{{scope.row.index}}</template>
            </el-table-column>
            <el-table-column prop="name" label="键">
              <template v-slot="scope">
                <el-input size="small" v-model="scope.row.key" type="text" :maxlength="20"  placeholder="请输入key"/>
              </template>
            </el-table-column>
            <el-table-column prop="value" label="值">
              <template v-slot="scope">
                <el-input size="small" v-model="scope.row.value" type="text" :maxlength="100"  placeholder="请输入value"/>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template v-slot="scope">
                <el-button size="small" type="danger" icon="el-icon-delete" @click="removeRow(scope)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="flex align-center justify-center" style="padding: 15px 0;">
            <el-button type="danger"  size="mini" @click="addRow" icon="el-icon-plus">添加</el-button>
          </div>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" icon="el-icon-check">确 定</el-button>
        <el-button @click="cancel" icon="el-icon-close">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listData, getData, delData, addData, updateData } from "@/api/system/dict/data";
import { optionselect as getDictOptionselect, getType } from "@/api/system/dict/type";
import {listApiInfo,addApiInfo,updateApiInfo,delApiInfo,getApiInfo} from "@/api/model/apiCollection"
export default {
  name: "apiCollection",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      dataList: [],
      // 默认字典类型
      defaultDictType: "",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      paramsData:[],
      // 数据标签回显样式
      requestMethodOption: [
        {
          value: "GET",
          label: "GET"
        },
        {
          value: "POST",
          label: "POST"
        },

      ],
      // 类型数据字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      basicInfoId:undefined,
      // 表单校验
      rules: {
        // dictLabel: [
        //   { required: true, message: "数据标签不能为空", trigger: "blur" }
        // ],

      }
    };
  },
  created() {
    // 模型基本信息表主键id
    const id = this.$route.params && this.$route.params.id;
    this.basicInfoId = id;
    this.getList(id);
  },
  methods: {

    /** 查询字典数据列表 */
    getList(id) {
      this.loading = true;
      this.queryParams['basicInfoId'] = id;
      listApiInfo(this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        serialNumber: undefined,
        description: undefined,
        requestUrl: undefined,
        requestMethod: undefined,
        requestHeader: undefined,
        requestParams: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 返回按钮操作 */
    handleClose() {
      const obj = { path: "/model/info" };
      this.$tab.closeOpenPage(obj);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加接口信息";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dictCode)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getApiInfo(id).then(response => {
        this.form = response.data;
        const params = this.form.requestParams;
        if(params){
          this.paramsData = JSON.parse(params);
        }
        this.open = true;
        this.title = "修改接口信息";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log('form',this.form);
          if (this.form.id !== void 0) {
        //    this.form.requestHeader = JSON.stringify(this.form.requestHeader);
            this.form.requestParams = JSON.stringify(this.paramsData);
            updateApiInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form['basicInfoId'] = this.basicInfoId;
        //    this.form.requestHeader = JSON.stringify(this.form.requestHeader);
            this.form.requestParams = JSON.stringify(this.paramsData);
            addApiInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认删除？').then(function() {
        return delApiInfo(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    addRow(){
      const len = this.paramsData.length;
      const obj = {
        key:'',
        value:'',
        index:len + 1,
      };
      this.paramsData.push(obj);
    },
    removeRow(scope){
      const index = scope.$index;
      if(index !== -1){
        this.paramsData.splice(index,1);
      }
      for (const i in this.paramsData) {
         this.paramsData[i].index = Number(i) + 1;
      }
    }
  }
};
</script>
